/*
 * @Author: yangy
 * @Date: 2023-11-07 14:12:20
 * @LastEditors: yangy aidreams@sina.com
 * @LastEditTime: 2024-03-08 16:02:03
 * @FilePath: /qn_mall_frontend/src/components/index.js
 * @Description:
 *
 * Copyright (c) 2023 by 青柠利合科技(北京)有限公司, All Rights Reserved.
 */
function capitalizeFirstLetter(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

function validateFileName(str) {
  return (
    /^\S+\.vue$/.test(str) &&
    str.replace(/^\S+\/(\w+)\.vue$/, (rs, $1) => capitalizeFirstLetter($1))
  );
}

// vite 下不再使用require
// const requireComponent = require.context(".", true, /\.vue$/);
const requireComponent = import.meta.glob("./**/*.vue", { eager: true });
export default {
  install(app) {
    // 找到组件文件夹下以.vue命名的文件，如果文件名为index，那么取组件中的name作为注册的组件名
    requireComponent.keys().forEach((filePath) => {
      const componentConfig = requireComponent(filePath);
      console.log(componentConfig);
      const fileName = validateFileName(filePath);
      const componentName =
        fileName.toLowerCase() === "index"
          ? capitalizeFirstLetter(componentConfig.default.name)
          : fileName;
      app.component(componentName, componentConfig.default || componentConfig);
    });
  },
};
